package com.googlecode.jmicroerp.security;

import com.googlecode.jmicroerp.wicket.JmicroerpApplication;
import com.googlecode.jmicroerp.wicket.SecuredWebSession;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.wicketstuff.security.authentication.LoginException;
import org.wicketstuff.security.hive.authentication.LoginContext;
import org.wicketstuff.security.hive.authentication.Subject;

/**
 *
 * @author alex
 */
public class SpringLoginContext extends LoginContext {

    private AbstractAuthenticationToken token;

    public SpringLoginContext(String username, String pass) {
        this(new UsernamePasswordAuthenticationToken(username, pass));
    }
    
    public SpringLoginContext(AbstractAuthenticationToken token) {
        super();
        this.token = token;
    }

    private void setAuthentication(Authentication authentication) {
        SecurityContextHolder.getContext().setAuthentication(authentication);
    }

    @Override
    public Subject login() throws LoginException {
        if (token == null) {
            throw new LoginException("Insufficient information to login");
        }

        try {
            AuthenticationManager authenticationManager = JmicroerpApplication.get().getAuthenticationManager();
            if (authenticationManager == null) {
                throw new AssertionError(
                        "AuthenticationManager not found, check the spring configuration");
            }

            // Perform Spring Security authentication
            Authentication authResult = authenticationManager.authenticate(token);
            setAuthentication(authResult);

            // Convert the result to a Wicket object
            SpringSubject wicketSubject = new SpringSubject(authResult);
            
            // We will store it in our session to let the pages display the
            // user's details (this is purely optional, no need to do this to
            // handle authorizations)
            SecuredWebSession.get().setUserDetail(wicketSubject);
            wicketSubject.getUtilizator().getMagazin().getDenumire();
            SecuredWebSession.get().setMagazin(wicketSubject.getUtilizator().getMagazin());
            return wicketSubject;
        } catch (AuthenticationException e) {
            setAuthentication(null);
            throw new LoginException(e);
        } finally {
            token = null;
        }
    }
}
